import React, { useRef, useEffect, useState, ReactElement } from 'react';
import ReactDOM from 'react-dom';

const context: any = React.createContext({ path: '', setPath: () => {} });
const { Provider, Consumer } = context;

import { getHash, objToStringParams } from '@/utils/public';
import local from '@/utils/local';

export const Consumerp = Consumer;

// 路由组件
interface Props {
  // render?: Function;
  children?: any;
  keepAlive?: boolean;
  component?: any;
  // router: Router;
  path: string;
  a?: any;
}

// 路由组件
export function Route(props: Props) {
  const { path } = props;
  const prevPath = useRef('');

  return (
    <Consumer>
      {(value: any) => {
        const { routes, routesIndex } = value;
        // 页面跳转，路由进栈
        const push = (path: string, params: ObjAny) => {
          const paramString = objToStringParams(params as ObjAny);
          const _path = path + paramString;
          window.location.hash = _path;
          prevPath.current = routes[routesIndex]; // 前一个路由
          value.setRoutes([...value.routes, _path]); // 缓存添加路由
          value.setRoutesIndex(value.routesIndex + 1); // 当前索引指向最后一个路由地址
          value.setPath(_path);
        };
        // 路由重定向
        const replace = (path: string, params: ObjAny) => {
          const paramString = objToStringParams(params as ObjAny);
          const _path = path + paramString;
          window.location.hash = _path;
          prevPath.current = routes[routesIndex]; // 前一个路由
          value.setRoutes([_path]); // 缓存添加路由
          value.setRoutesIndex(0); // 当前索引指向最后一个路由地址
          value.setPath(_path);
        };
        if (props.children) {
          const pathList = path.split('/');
          const { length } = pathList;
          const hashList = getHash().split('/');
          let flag = false;
          hashList.forEach((item, index) => {
            if (index <= length - 1) {
              if (item === pathList[index]) {
                flag = true;
              } else {
                flag = false;
              }
            }
          });
          if (flag && path !== '/') {
            return React.Children.map(props.children, (child) => {
              console.log(path);
              return React.cloneElement(child, {
                router: {
                  replace,
                  push,
                  path: value.path,
                  prevPath: prevPath.current,
                },
              });
            });
          }
          return null;
        }
        return null;
      }}
    </Consumer>
  );
}

type Router = {
  push: Function;
  replace: Function;
  path: string;
};
type RedirectChildren = {
  to: string;
  routerPush: Function;
  router: Router;
};
export function RedirectChildren(props: RedirectChildren) {
  useEffect(() => {
    if (props.to && props.router.path === '/') {
      props.router.replace(props.to);
      props;
    }
  }, []);
  return null;
}

export function Redirect(props: any) {
  return (
    <Consumer>
      {(value: any) => {
        const setRouter = (path: string, params: ObjAny) => {
          const paramString = objToStringParams(params as ObjAny);
          const _path = path + paramString;
          window.location.hash = _path; // 设置浏览器hash路由
          // value.setPath(_path);
          value.setRoutes([...value.routes, _path]); // 缓存添加路由
          value.setRoutesIndex(value.routesIndex + 1); // 当前索引指向最后一个路由地址
          value.setPath(_path);
        };
        // 路由重定向
        const replace = (path: string, params: ObjAny) => {
          const paramString = objToStringParams(params as ObjAny);
          const _path = path + paramString;
          window.location.hash = _path; // 设置浏览器hash路由
          value.setRoutes([_path]); // 缓存添加路由
          value.setRoutesIndex(0); // 当前索引指向最后一个路由地址
          value.setPath(_path);
        };
        return <RedirectChildren router={{ push: setRouter, replace, path: value.path }} {...props}></RedirectChildren>;
      }}
    </Consumer>
  );
}

export function HashRouter(props: any) {
  const [path, setPath] = useState('/');
  const [routes, setRoutes] = useState(['/']);
  const [routesIndex, setRoutesIndex] = useState(0);
  // // 监听hash路由改变
  // const onHashchange = (hash: HashChangeEvent) => {
  //   setPath(window.location.hash.slice(1).split('?')[0]);
  // };
  // 监听浏览器前进后退
  const popstate = () => {
    const back = routes[routesIndex - 1];
    const forword = routes[routesIndex + 1];
    const _hash = getHash();
    if (!back) {
      history.forward();
      return;
    }
    if (back === _hash) {
      setPath(back);
      return;
    }
    if (forword === _hash) {
      setPath(forword);
    }
  };

  useEffect(() => {
    window.addEventListener('popstate', popstate);
    return () => {
      window.removeEventListener('popstate', popstate);
    };
  }, [routes]);

  // 监听路由变化-保存当前路由栈到本地session
  useEffect(() => {
    local.sessionSet('routes', routes);
    local.sessionSet('routesIndex', routesIndex);
  }, [routes]);

  return <Provider value={{ path, setPath, setRoutes, setRoutesIndex, routes, routesIndex }}>{props.children}</Provider>;
}
